package com.hoongs.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoongs.v1.dto.RiderPageDto;
import com.hoongs.v1.entity.Address;
import com.hoongs.v1.entity.Order;
import com.hoongs.v1.entity.Rider;
import com.hoongs.v1.entity.User;
import com.hoongs.v1.mapper.AddressMapper;
import com.hoongs.v1.mapper.OrderMapper;
import com.hoongs.v1.mapper.RiderMapper;
import com.hoongs.v1.mapper.UserMapper;
import com.hoongs.v1.service.RiderService;
import com.hoongs.v1.utils.JwtUtil;
import com.hoongs.v1.utils.PResult;
import com.hoongs.v1.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;

@Service
public class RiderServiceImpl implements RiderService {

    public static final String NOT_FOUND_ARTICLE = "没有找到该骑手！";

    @Resource
    private RiderMapper riderMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AddressMapper addressMapper;

    @Override
    @Transactional
    public Result add(Rider rider) {
        rider.setUserId(JwtUtil.getUUID());
        if (riderMapper.insert(rider) == 1) {
            User user = Rider.toUser(rider);
            userMapper.insert(user);
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    @Transactional
    public Result remove(String id) {
        if (!findRiderById(id)) return Result.opError(NOT_FOUND_ARTICLE);
        Rider rider = riderMapper.selectById(id);
        if (riderMapper.deleteById(id) == 1 && userMapper.deleteById(rider.getUserId()) == 1) {
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    public Result update(Rider rider) {
        if (!findRiderById(rider.getId())) return Result.opError(NOT_FOUND_ARTICLE);
        if (riderMapper.updateById(rider) == 1) {
            User user = Rider.toUser(rider);
            userMapper.updateById(user);
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    public Result selectById(String id) {
        Rider rider = riderMapper.selectById(id);
        if (rider == null) return Result.error(NOT_FOUND_ARTICLE);
        return Result.success(rider);
    }

    @Override
    public Result selectList(String name, String mobile) {
        QueryWrapper<Rider> wrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(name)) {
            wrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(mobile)) {
            wrapper.like("mobile", mobile);
        }
        Collection<Rider> list = riderMapper.selectList(wrapper);
        for (Rider rider : list) {
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("status", "1");
            orderQueryWrapper.eq("rider_id", rider.getId());
            BigDecimal num = BigDecimal.valueOf(orderMapper.selectCount(orderQueryWrapper));
            rider.setOrderNum(num);
        }
        return Result.success(list);
    }

    @Override
    public Result selectPageList(RiderPageDto riderPageDto) {
        if (!PResult.checkPageQuery(riderPageDto.getPage(), riderPageDto.getSize())) return Result.error("分页参数错误");

        Page<Rider> daoPage = new Page<>(riderPageDto.getPage(), riderPageDto.getSize());
        QueryWrapper<Rider> wrapper = new QueryWrapper<Rider>();
        if (StringUtils.isNotBlank(riderPageDto.getName())) {
            wrapper.like("name", riderPageDto.getName());
        }
        if (StringUtils.isNotBlank(riderPageDto.getStatus())) {
            wrapper.eq("status", riderPageDto.getStatus());
        }
        if (StringUtils.isNotBlank(riderPageDto.getMobile())) {
            wrapper.like("mobile", riderPageDto.getMobile());
        }
        IPage<Rider> riderDaoIPage = riderMapper.selectPage(daoPage, wrapper);
        PResult rs = new PResult(riderDaoIPage);
        return Result.success(rs);
    }

    @Override
    public Result selectOrderList(String status, String token) {
        User user = UserServiceImpl.getUserInfoByToken(token, userMapper);
        Rider rider = riderMapper.selectOne(new QueryWrapper<Rider>().eq("user_id", user.getId()));
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper
                .eq("rider_id", rider.getId())
                .eq("status", status)
                .orderByDesc("send_time")
                .orderByDesc("create_time");
        List<Order> orderList = orderMapper.selectList(wrapper);
        for (Order order : orderList) {
            Address address = addressMapper.selectById(order.getUserAddress());
            order.setUserAddress(address.getAddress() + " " + address.getAddressDetail());
        }
        return Result.success(orderList);
    }

    /**
     * 根据Id查询骑手是否存在
     */
    public Boolean findRiderById(String id) {
        Rider rider = riderMapper.selectById(id);
        return rider != null;
    }
}
